import { getToken, setToken as setTokenLocal, removeToken as removeTokenLocal} from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'

const state = {
  token: getToken() || null,
  userInfo: {}
}

const mutations = {
  setToken(state, token) {
    state.token = token

    setTokenLocal(token)
  },
  removeToken(state) {
    state.token = null

    removeTokenLocal()
  },
  setUserInfo(state, result) {
    state.userInfo = { ...result }
  },
  reomveUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async login(context, data) {
    const res = await login(data)

    context.commit('setToken', res)
  },
  async getUserInfo (context) {
    const result = await getUserInfo()
    const baseInfo = await getUserDetailById(result.userId)

    const userInfo = {...result, ...baseInfo}

    context.commit('setUserInfo', userInfo)
    return userInfo
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
